﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenServe.Net.Library.Extentions;
using Newtonsoft.Json;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace OpenServe.Net.Messaging {
    #region typed
    public class Message<T> where T : new() {
        public Header Header { get; set; }
        private T body;

        public T Body {
            get { return body; }
            set { body = value; Header.ContainingType = body.GetType(); }
        }

        public Message() {  }
        public Message(Header header, T body) {
            Header = header; Body = body;
        }
        public Message(string json) {
            var parts = json.Split(new []{"::"}, StringSplitOptions.RemoveEmptyEntries);
            Header = JsonConvert.DeserializeObject<Header>(parts[0]);
            Body = JsonConvert.DeserializeObject<T>(parts[1]);
        }
        public string ToJson() {
            return "{0}::{1}".format(JsonConvert.SerializeObject(Header),JsonConvert.SerializeObject(Body));
        }
    }
    #endregion
    [Serializable]
    public class Message {
        public Header Header { get; set; }
        private object body;

        public object Body {
            get { return body; }
            set { body = value; Header.ContainingType = body.GetType(); }
        }

        public Message() { }
        public Message(Header header, object body) {
            Header = header; Body = body;
        }
        public Message(string json) {
            var parts = json.Split(new[] { "~:~:~" }, StringSplitOptions.RemoveEmptyEntries);
            Header = JsonConvert.DeserializeObject<Header>(parts[0]);
            Body = JsonConvert.DeserializeObject(parts[1], Header.ContainingType);
        }
        public string ToJson() {
            return "{0}~:~:~{1}".format(JsonConvert.SerializeObject(Header), JsonConvert.SerializeObject(Body));
        }

    }
}
